package pers.lmy.stockTrading.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.lmy.stockTrading.entity.User;
import pers.lmy.stockTrading.service.StockService;
import pers.lmy.stockTrading.service.UserService;

import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService = new UserService();

    @PostMapping("/login")
    public JSONObject login(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String token = UUID.randomUUID().toString();
        List<User> list = userService.login(username, password);
        JSONObject json = new JSONObject();
        if (list.isEmpty()) {
            json.put("message", "failed");
        } else {
            json.put("message", "success");
            json.put("id", list.get(0).getUserid());
            json.put("username", username);
            json.put("password", password);
            json.put("token", token);
        }
        return json;
    }

    @PostMapping("/register")
    public JSONObject register(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        List<User> list = userService.register(username, password);
        JSONObject json = new JSONObject();
        if (!list.isEmpty()) {
            json.put("message", "failed");
        } else {
            json.put("message", "success");
        }
        return json;
    }
}
